package com.yls.except.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TestOCR {

	// 可以参考
	// http://bbs.apistore.baidu.com/forum.php?mod=viewthread&tid=753&extra=

	@SuppressWarnings({ "deprecation", "static-access" })
	public static void main(String[] args) {
		String httpUrl = "http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid";
		String httpArg = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=";
		Base64 base64 = new Base64();
		httpArg += URLEncoder
				.encode(base64
//						.encode(getBytes("e:\\2.png")));
						.encode(getBytes("D:\\2.jpg")));
		String jsonResult = request(httpUrl, httpArg);
		System.out.println(jsonResult);
		Map<String, Object> json = GeneralResult.jsonStrToMap(jsonResult);
		json = returnMap(json);
		System.out.println(json);
	}

	// 图片转码的部分请参考
	// http://bbs.apistore.baidu.com/forum.php?mod=viewthread&tid=753&extra=

	/**
	 * @param httpUrl
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String request(String httpUrl, String httpArg) {
	    BufferedReader reader = null;
	    String result = null;
	    StringBuffer sbf = new StringBuffer();

	    try {
	        URL url = new URL(httpUrl);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type",
	                        "application/x-www-form-urlencoded");
	        // 填入apikey到HTTP header
	        connection.setRequestProperty("apikey", "1353ab869c123b51b7d35d77af389612");
	        connection.setDoOutput(true);
	        connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
	        connection.connect();
	        InputStream is = connection.getInputStream();
	        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	        String strRead = null;
	        while ((strRead = reader.readLine()) != null) {
	            sbf.append(strRead);
	            sbf.append("\r\n");
	        }
	        reader.close();
	        result = sbf.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;


}

	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	@SuppressWarnings({ "static-access", "deprecation" })
	public static Map<String, Object> getTextInfo(String path) {
		String httpUrl = "http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid";
		String httpArg = "fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=";
		Base64 base64 = new Base64();
		httpArg += URLEncoder.encode(base64.encode(getBytes(path)));
		String jsonResult = request(httpUrl, httpArg);
		System.out.println(jsonResult);
		Map<String, Object> json = GeneralResult.jsonStrToMap(jsonResult);
		json = returnMap(json);
		return json;
	}

	public static Map<String, Object> returnMap (Map<String, Object> map) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String errNum = map.get("errNum") + "";
		String errMsg = map.get("errMsg") + "";
		if(!"0".equals(errNum) && !"success".equals(errMsg)) {
			returnMap.put("tag", "-1");
			returnMap.put("message", errMsg);
			return returnMap;
		}
		JSONArray retData = (JSONArray) map.get("retData");
		if(retData == null || retData.length() <= 0) {
			returnMap.put("tag", "-2");
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		}
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < retData.length(); i++) {
			Map<String, Object> datamap = new HashMap<String, Object>();
			try {
				JSONObject jsonObject = (JSONObject) retData.get(i);
				JSONObject rect = (JSONObject) jsonObject.get("rect");
				datamap.put("word", jsonObject.get("word"));
				datamap.put("height", rect.get("height"));
				datamap.put("width", rect.get("width"));
				datamap.put("left", rect.get("left"));
				datamap.put("top", rect.get("top"));
				list.add(datamap);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		Map<String, Map<String, Object>> caseMap = new
				HashMap<String, Map<String, Object>>();

		if(list == null || list.size() <= 0) {
			returnMap.put("tag", -2);
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		}
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> maplist = list.get(i);
			String word = maplist.get("word") + "";
			for (int j = 0; j < 14; j++) {
				switch (j) {
				case 0:
					if(word.contains("病例名称"))
						caseMap.put("casename", maplist);
					break;
				case 1:
					if(word.contains("姓名") || word.contains("名字"))
						caseMap.put("name", maplist);
					break;
				case 2:
					if(word.contains("性别"))
						caseMap.put("sex", maplist);
					break;
				case 3:
					if(word.contains("年龄"))
						caseMap.put("age", maplist);
					break;
				case 4:
					if(word.contains("电话") || word.contains("手机"))
						caseMap.put("phone", maplist);
					break;
				case 5:
					if(word.contains("身高"))
						caseMap.put("height", maplist);
					break;
				case 6:
					if(word.contains("体重"))
						caseMap.put("weight", maplist);
					break;
				case 7:
					if(word.contains("血型"))
						caseMap.put("blood", maplist);
					break;
				case 8:
					if(word.contains("职业"))
						caseMap.put("job", maplist);
					break;
				case 9:
					if(word.contains("备注"))
						caseMap.put("remark", maplist);
					break;
				case 10:
					if(word.contains("描述"))
						caseMap.put("desc", maplist);
					break;
				case 11:
					if(word.contains("过敏史"))
						caseMap.put("allergy", maplist);
					break;
				case 12:
					if(word.contains("既往史"))
						caseMap.put("previons", maplist);
					break;
				case 13:
					if(word.contains("用药处方"))
						caseMap.put("overcounter", maplist);
					break;
				default:
					break;
				}
			}
		}
		if(caseMap == null || caseMap.size() <= 0) {
			returnMap.put("tag", -2);
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		}
		returnMap = new HashMap<String, Object>();
		if(list == null || list.size() <= 0) {
			returnMap.put("tag", -2);
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		}
		if(caseMap == null || caseMap.size() <= 0){
			returnMap.put("tag", -2);
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		}
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> maplist = list.get(i);
			int top = Integer.parseInt(maplist.get("top") + "");
			String word = maplist.get("word") + "";
			Map<String, Object> name = caseMap.get("name");
			Map<String, Object> casename = caseMap.get("casename");
			Map<String, Object> age = caseMap.get("age");
			Map<String, Object> sex = caseMap.get("sex");
			Map<String, Object> phone = caseMap.get("phone");
			Map<String, Object> height = caseMap.get("height");
			Map<String, Object> weight = caseMap.get("weight");
			Map<String, Object> blood = caseMap.get("blood");
			Map<String, Object> job = caseMap.get("job");
			Map<String, Object> remark = caseMap.get("remark");
			Map<String, Object> desc = caseMap.get("desc");
			Map<String, Object> allergy = caseMap.get("allergy");
			Map<String, Object> previons = caseMap.get("previons");
			Map<String, Object> overcounter = caseMap.get("overcounter");
			int casenametop = 0;
			int nametop = 0;
			int agetop = 0;
			int sextop = 0;
			int phonetop = 0;
			int weighttop = 0;
			int heighttop = 0;
			int bloodtop = 0;
			int jobtop = 0;
			int remarktop = 0;
			int desctop = 0;
			int allergytop = 0;
			int previonstop = 0;
			int overcountertop = 0;
			if(casename != null && !StringIsempty.isallempty(casename.get("top") + ""))
				casenametop = Integer.parseInt(casename.get("top") + "");
			if(name != null && !StringIsempty.isallempty(name.get("top") + ""))
				nametop = Integer.parseInt(name.get("top") + "");
			if(age != null && !StringIsempty.isallempty(age.get("top") + ""))
				agetop = Integer.parseInt(age.get("top") + "");
			if(sex != null && !StringIsempty.isallempty(sex.get("top") + ""))
				sextop = Integer.parseInt(sex.get("top") + "");
			if(phone != null && !StringIsempty.isallempty(phone.get("top") + ""))
				phonetop = Integer.parseInt(phone.get("top") + "");
			if(height != null && !StringIsempty.isallempty(height.get("top") + ""))
				heighttop = Integer.parseInt(height.get("top") + "");
			if(weight != null && !StringIsempty.isallempty(weight.get("top") + ""))
				weighttop = Integer.parseInt(weight.get("top") + "");
			if(blood != null && !StringIsempty.isallempty(blood.get("top") + ""))
				bloodtop = Integer.parseInt(blood.get("top") + "");
			if(job != null && !StringIsempty.isallempty(job.get("top") + ""))
				jobtop = Integer.parseInt(job.get("top") + "");
			if(remark != null && !StringIsempty.isallempty(remark.get("top") + ""))
				remarktop = Integer.parseInt(remark.get("top") + "");
			if(desc != null && !StringIsempty.isallempty(desc.get("top") + ""))
				desctop = Integer.parseInt(desc.get("top") + "");
			if(allergy != null && !StringIsempty.isallempty(allergy.get("top") + ""))
				allergytop = Integer.parseInt(allergy.get("top") + "");
			if(previons != null && !StringIsempty.isallempty(previons.get("top") + ""))
				previonstop = Integer.parseInt(previons.get("top") + "");
			if(overcounter != null && !StringIsempty.isallempty(overcounter.get("top") + ""))
				overcountertop = Integer.parseInt(overcounter.get("top") + "");
			if(casenametop >= top - 10 && casenametop <= top + 10 && !word.contains("病例名称"))
				returnMap.put("casename", word);
			else if(nametop >= top - 10 && nametop <= top + 10 && !word.contains("姓名"))
				returnMap.put("name", word);
			else if(agetop >= top - 10 && agetop <= top + 10 && !word.contains("年龄"))
				returnMap.put("age", word);
			else if(sextop >= top - 10 && sextop <= top + 10 &&  !word.contains("性别"))
				returnMap.put("sex", word);
			else if(phonetop >= top - 10 && phonetop <= top + 10 &&  !word.contains("电话"))
				returnMap.put("phone", word);
			else if(heighttop >= top - 10 && heighttop <= top + 10 &&  !word.contains("身高"))
				returnMap.put("height", word);
			else if(weighttop >= top - 10 && weighttop <= top + 10 &&  !word.contains("体重"))
				returnMap.put("weight", word);
			else if(bloodtop >= top - 10 && bloodtop <= top + 10 &&  !word.contains("血型"))
				returnMap.put("blood", word);
			else if(jobtop >= top - 10 && jobtop <= top + 10 &&  !word.contains("职业"))
				returnMap.put("job", word);
			else if(remarktop >= top - 10 && remarktop <= top + 10 &&  !word.contains("备注"))
				returnMap.put("remark", word);
			else if(desctop >= top - 10 && desctop <= top + 10 &&  !word.contains("描述"))
				returnMap.put("desc", word);
			else if(allergytop >= top - 10 && allergytop <= top + 10 &&  !word.contains("过敏史"))
				returnMap.put("previons", word);
			else if(previonstop >= top - 10 && previonstop <= top + 10 && !word.contains("既往史"))
				returnMap.put("overcounter", word);
			else if(overcountertop >= top - 10 && overcountertop <= top + 10 && !word.contains("用户处方"))
				returnMap.put("phone", word);
		}
		if(returnMap == null || returnMap.size() <= 0) {
			returnMap.put("tag", -2);
			returnMap.put("message", "病例识别失败，请尝试上传高清的病例");
			return returnMap;
		} else {
			String casename = returnMap.get("casename") + "";
			String name = returnMap.get("name") + "";
			String age = returnMap.get("age") + "";
			String sex = returnMap.get("sex") + "";
			String phone = returnMap.get("phone") + "";
			String height = returnMap.get("height") + "";
			String weight = returnMap.get("weight") + "";
			String blood = returnMap.get("blood") + "";
			String job = returnMap.get("job") + "";
			String remark = returnMap.get("remark") + "";
			String desc = returnMap.get("desc") + "";
			String allergy = returnMap.get("allergy") + "";
			String previons = returnMap.get("previons") + "";
			String overcounter = returnMap.get("overcounter") + "";
			if(StringIsempty.isallempty(casename))
				returnMap.put("casename", "");
			else {
				casename = casename.replace(":", "").replace("病例名称", "");
				returnMap.put("casename", casename);
			}
			if(StringIsempty.isallempty(name))
				returnMap.put("name", "");
			else {
				name = name.replace(":", "").replace("姓名", "");
				returnMap.put("name", name);
			}
			if(StringIsempty.isallempty(age))
				returnMap.put("age", "0");
			else {
				age = age.replace(":", "").replace("年龄", "");
				returnMap.put("age", age);
			}
			if(StringIsempty.isallempty(sex))
				returnMap.put("sex", "男");
			else {
				sex = sex.replace(":", "").replace("性别", "");
				returnMap.put("sex", sex);
			}
			if(StringIsempty.isallempty(phone))
				returnMap.put("phone", "");
			else {
				phone = phone.replace(":", "").replace("电话", "").replace("手机", "").replace("号", "").replace("码", "");
				returnMap.put("phone", phone);
			}
			if(StringIsempty.isallempty(height))
				returnMap.put("height", "");
			else {
				height = height.replace(":", "").replace("身高", "");
				returnMap.put("height", height);
			}
			if(StringIsempty.isallempty(weight))
				returnMap.put("weight", "");
			else {
				weight = weight.replace(":", "").replace("体重", "");
				returnMap.put("weight", weight);
			}
			if(StringIsempty.isallempty(blood))
				returnMap.put("blood", "");
			else {
				blood = blood.replace(":", "").replace("血型", "");
				returnMap.put("blood", blood);
			}
			if(StringIsempty.isallempty(job))
				returnMap.put("job", "");
			else {
				job = job.replace(":", "").replace("职业", "");
				returnMap.put("job", job);
			}
			if(StringIsempty.isallempty(remark))
				returnMap.put("remark", "");
			else {
				remark = remark.replace(":", "").replace("备注", "");
				returnMap.put("remark", remark);
			}
			if(StringIsempty.isallempty(desc))
				returnMap.put("desc", "");
			else {
				desc = desc.replace(":", "").replace("描述", "");
				returnMap.put("desc", desc);
			}
			if(StringIsempty.isallempty(allergy))
				returnMap.put("allergy", "");
			else {
				allergy = allergy.replace(":", "").replace("过敏史", "");
				returnMap.put("allergy", allergy);
			}
			if(StringIsempty.isallempty(previons))
				returnMap.put("previons", "");
			else {
				previons = previons.replace(":", "").replace("既往史", "");
				returnMap.put("previons", previons);
			}
			if(StringIsempty.isallempty(overcounter))
				returnMap.put("overcounter", "");
			else {
				overcounter = overcounter.replace(":", "").replace("用药处方", "");
				returnMap.put("overcounter", overcounter);
			}
			returnMap.put("tag", 1);
		}
		return returnMap;
	}
}
